<?php

class Admin_Upload_Model extends Model
{
	// find a way to use variable to reuse the code by recalling the same method
	var $images_dir;
	var $images_dir_url;
	
	public function __construct()
	{
		parent::Model();
		$this->images_dir = realpath(APPPATH.'../images/');
		$this->images_dir_url = base_url().'images/';
		
		// open the database
		$this->load->database();
	}

	function do_upload()
	{ 
		$newfilename=0;
	
		$config = array(
			'allowed_types' => 'jpeg|jpg|png|gif',
			'upload_path' => $this->images_dir,
			'max_size' => 3000
		);

		$this->load->library('upload',$config);

		$upload_return=$this->upload->do_upload();

		if($upload_return)
		{
			// this fetches the image folder from where ever
			$image_date = $this->upload->data();

			$config = array(
				'source_image' => $image_date['full_path'],
				'new_image' => $this->images_dir.'/thumbs',
				'maintain_ration' => true,
				'height' => 100,
				'width' =>  100
			);


			$this->load->library('image_lib',$config);
			$this->image_lib->resize(); // resizes it to thumb nail version

			//new file name will be changed to
			$file_count=$this->db->count_all('file_info')+1;

			$newfilename = $image_date['file_name'];

			//renaming the name of the last uploaded file from the folder
			rename($image_date['full_path'], $image_date['file_path'].$newfilename);
			rename($image_date['file_path']."thumbs/".$image_date['file_name'], $image_date['file_path']."thumbs/".$newfilename);
																	  
		}
		
		return $newfilename;
	}
	
	//reading file of the directory; NOT USED ANYMORE
	function get_images()
	{
		$files = scandir($this->images_dir);
		$files = array_diff($files,array('.','..', 'thumbs'));

		$images =array();

		foreach($files as $file)
		{
			$images[$file][]=array(
				'name' => $file,
				'caption' => "",
				'url' => $this->images_dir_url.$file,
				'thumb_url' => $this->images_dir_url.'thumbs/'.$file
			);
		}
		
		return $images;
	}
	
}
?>